package cn.xdf.docscan.util

import android.graphics.*

object ImageWarp {
    /**
     * 将四边形区域透视矫正为矩形。
     * corners 需按顺序: 左上, 右上, 右下, 左下
     */
    fun warpQuadToRect(src: Bitmap, corners: List<PointF>): Bitmap? {
        if (corners.size != 4) return null
        val (tl, tr, br, bl) = corners
        val topW = distance(tl, tr)
        val bottomW = distance(bl, br)
        val leftH = distance(tl, bl)
        val rightH = distance(tr, br)
        val outW = maxOf(topW, bottomW).toInt().coerceAtLeast(1)
        val outH = maxOf(leftH, rightH).toInt().coerceAtLeast(1)

        val dst = floatArrayOf(
            0f, 0f,
            outW.toFloat(), 0f,
            outW.toFloat(), outH.toFloat(),
            0f, outH.toFloat()
        )
        val srcPts = floatArrayOf(
            tl.x, tl.y,
            tr.x, tr.y,
            br.x, br.y,
            bl.x, bl.y
        )
        val matrix = Matrix()
        matrix.setPolyToPoly(srcPts, 0, dst, 0, 4)
        val out = Bitmap.createBitmap(outW, outH, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(out)
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        canvas.drawBitmap(src, matrix, paint)
        return out
    }

    private fun distance(a: PointF, b: PointF): Float {
        val dx = a.x - b.x
        val dy = a.y - b.y
        return kotlin.math.hypot(dx.toDouble(), dy.toDouble()).toFloat()
    }
}


